//
//  XLogBridge.m
//  ACFrameworkSwift
//
//  Created by fisherman on 2021/9/2.
//

#import "XLogBridge.h"
#import <mars/xlog/appender.h>
#import <mars/xlog/xloggerbase.h>

static NSUInteger g_processID = 0;

@implementation XLogBridge

// 配置
+ (void)configWithLogPath: (NSString *)logPath pubkey: (NSString *)pubkey maxSize: (uint64_t)maxSize nameprefix: (NSString *)nameprefix {
    #if DEBUG
    xlogger_SetLevel(kLevelDebug);
    appender_set_console_log(true);
    #else
    xlogger_SetLevel(kLevelInfo);
    appender_set_console_log(false);
    #endif
    
    appender_set_max_file_size(maxSize);
    
    XLogConfig config;
    config.logdir_ = [logPath UTF8String];
    config.mode_ = kAppenderAsync;
    config.pub_key_ = [pubkey UTF8String];
    config.nameprefix_ = [nameprefix UTF8String];
    appender_open(config);
}

// 单条 log 的写入
+ (void)logWithLevel: (TLogLevel)logLevel tag: (const char*)tag fileName:(const char*)fileName lineNumber: (int)lineNumber funcName: (const char*)funcName message: (NSString *)message {
    XLoggerInfo info;
    info.level = logLevel;
    info.tag = tag;
    info.filename = fileName;
    info.func_name = funcName;
    info.line = lineNumber;
    gettimeofday(&info.timeval, NULL);
    info.tid = (uintptr_t)[NSThread currentThread];
    info.maintid = (uintptr_t)[NSThread mainThread];
    info.pid = g_processID;
    xlogger_Write(&info, message.UTF8String);
}

+ (void)logWithLevel:(TLogLevel)logLevel tag:(const char*)tag fileName:(const char*)fileName lineNumber:(int)lineNumber funcName:(const char*)funcName format:(NSString *)format, ... {
    if ([self shouldLog:logLevel]) {
        va_list argList;
        va_start(argList, format);
        NSString* message = [[NSString alloc] initWithFormat:format arguments:argList];
        [self logWithLevel:logLevel tag:tag fileName:fileName lineNumber:lineNumber funcName:funcName message:message];
        va_end(argList);
    }
}

// 根据设置的最低 log 级别来判断是否能写入
+ (BOOL)shouldLog: (TLogLevel)level {
    if (level >= xlogger_Level()) {
        return YES;
    }
    return NO;
}

+ (void)close {
    appender_close();
}

@end
